﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ElectricalTest
{
    public class NpoiExport<T> where T : class
    {
        public static void SaveXlsChangeds(string xlsName, List<T> data)
        {
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Sheet1");
            sheet.CreateFreezePane(10, 1);

            //IRow row = sheet.CreateRow(0);
            //row.Height = 200 * 5;
            //row.CreateCell(0).SetCellValue()
            //for (int ii = 0; ii < 10; ii++)
            //{
            //    sheet.SetColumnWidth(ii, 20 * 256);

            //}
            //sheet.DefaultRowHeight = 600;


            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.Alignment = HorizontalAlignment.Center;
            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;

            var row = sheet.CreateRow(sheet.LastRowNum);
            int column = row.PhysicalNumberOfCells;


            int i = 0;

            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            foreach (var property in propertyInfos)
            {
                object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objs.Length > 0)
                {
                    row.CreateCell(i).SetCellValue(((DescriptionAttribute)objs[0]).Description);
                    i++;
                }
            }

            int j = sheet.LastRowNum + 1, n;
            foreach (var item in data)
            {
                n = 0;
                row = sheet.CreateRow(j++);
                var itemProps = item.GetType().GetProperties();
                foreach (var itemPropSub in itemProps)
                {
                    var objs = itemPropSub.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (objs.Length > 0)
                    {
                        row.CreateCell(n).SetCellValue(itemPropSub.GetValue(item, null) == null ? ""
                            : itemPropSub.GetValue(item, null).ToString());
                        n++;
                    }
                }
            }

            MemoryStream ms = new MemoryStream();

            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            FileStream fileStream = new FileStream(xlsName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            ms.WriteTo(fileStream);
            ms.Close();
            ms.Dispose();
            fileStream.Close();
            workbook.Close();
        }
    }
}
